<?php

namespace App\Http\Controllers\OpenShop\Feishu;

use App\Enums\OpenShop\InvestmentPromotion\ErrCode;
use App\Enums\OpenShop\InvestmentPromotion\OrganizationManageEnum;
use App\Enums\OpenShop\User\CodeEnum;
use App\Enums\Workflow\WorkflowEnum;
use App\Http\Controllers\BaseController;
use App\Http\Middleware\OpenShop\FeishuWebAuth;
use App\Http\Validate\OpenShop\InvestmentPromotion\OrganizationValidate;
use App\Models\OpenShop\Common\OpenShopOrderManagerModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopAddressModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageUserModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationRegionMappingModel;
use App\Remote\Rms\RmsCacheRemote;
use App\Service\BaseService;
use App\Service\OpenShop\Feishu\MainProcessService;
use App\Service\OpenShop\Feishu\OrderManagerService;
use App\Service\OpenShop\Feishu\OrganizationManageService;
use App\Service\OpenShop\Feishu\OrganizationManageUserService;
use App\Service\OpenShop\User\RmsUserService;
use App\Service\Workflow\WorkflowHandlerUserService;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class OrganizationManageController extends BaseController
{

    /**
     * 获取组织管理列表
     * @param Request $request
     * @return JsonResponse
     */
    public function list(Request $request)
    {
        $organizationList = OrganizationManageService::getOrganizationList();
        return $this->success($organizationList);
    }

    /**
     * 根据id修改组织管理信息
     * @param Request $request
     * @return JsonResponse
     * @throws GuzzleException
     */
    public function updateOrganizationById(Request $request): JsonResponse
    {
        $data        = OrganizationValidate::updateValidate($request->all());
        $manageId    = $data['manageId'];
        $mappingData = $data['mappingData'];
        $manageData  = [
            'name'                 => $data['name'],
            'type'                 => $data['type'],
            'developName'          => $data['developName'],
            'preparationName'      => $data['preparationName'],
            'developUid'           => $data['developUid'],
            'preparationUid'       => $data['preparationUid'],
            'designerUid'          => $data['designerUid'] ?? 0,
            'designerName'         => $data['designerName'] ?? '',
            'operationUid'         => $data['operationUid'],
            'operationName'        => $data['operationName'],
            'operationAttacheUser' => $data['operationAttacheUser'],
            "attendanceUser"       => json_encode($data["attendanceUser"], JSON_UNESCAPED_UNICODE)
        ];
        $rmsUserId = $request->user()->id;

        // 省区负责的provinceCodes
        $relationProvinceCodes = array_column($mappingData, 'provinceCode');


        // 城市经理 - 运营城市经理
        OrganizationManageUserService::addUser($manageId, OpenShopOrganizationManageUserModel::TYPE_CITY_MANAGER,
            $request->get('cityManagers'), $relationProvinceCodes);

        // 开发城市经理
        OrganizationManageUserService::addUser(
            $manageId, OpenShopOrganizationManageUserModel::TYPE_DEVELOP_CITY_MANAGER,
            $request->get('developCityManagers'), $relationProvinceCodes
        );

        //省区开发添加
        /*$developmentUserQuery = OpenShopOrganizationManageUserModel::query()
                                                                   ->withoutGlobalScope("isDel")
                                                                   ->where("manageId", $manageId)
                                                                   ->where("type",
                                                                       OpenShopOrganizationManageUserModel::TYPE_SITE_SELECTION_DEVELOPMENT);

        $existsDevelopmentUser = (clone $developmentUserQuery)->get();
        (clone $developmentUserQuery)->update([
            "isDeleted"    => 1,
            "updatedAt"    => time(),
            'updatedByUid' => $request->user()->id
        ]);
        if (!empty($data["provinceDevelopmentUser"])) {
            $normalUidGroup = array_intersect(
                array_column($data["provinceDevelopmentUser"], "uid"),
                $existsDevelopmentUser->pluck("userId")->toArray()
            );
            if ($normalUidGroup) {
                //已存在数据置为正常
                (clone $developmentUserQuery)->whereIn("userId", $normalUidGroup)->update([
                    "addressCodes" => null,
                    "isDeleted"    => 0,
                    "updatedAt"    => time(),
                    'updatedByUid' => $request->user()->id
                ]);
            }

            $notExistsUidGroup = array_diff(array_column($data["provinceDevelopmentUser"], "uid"), $normalUidGroup);
            if ($notExistsUidGroup) {
                //不存在数据新增记录
                OpenShopOrganizationManageUserModel::query()->insert(
                    collect($data["provinceDevelopmentUser"])->whereIn("uid", $notExistsUidGroup)->map(function (
                        $developmentUser
                    ) use ($manageId, $request) {
                        return [
                            'manageId'     => $manageId,
                            'name'         => $developmentUser['name'],
                            'type'         => OpenShopOrganizationManageUserModel::TYPE_SITE_SELECTION_DEVELOPMENT,
                            'userId'       => $developmentUser['uid'],
                            'createdByUid' => $request->user()->id,
                            'updatedByUid' => $request->user()->id,
                            "createdAt"    => time(),
                            "updatedAt"    => time()
                        ];
                    })->values()->toArray());
            }
        }*/

        // 稽核专员负责人
        OrganizationManageUserService::addUser(
            $manageId, OpenShopOrganizationManageUserModel::TYPE_CHECK_MANAGER,
            $request->get('checkManagers'), [], $rmsUserId
        );

//        OrganizationManageUserService::addUser($manageId,
//            OpenShopOrganizationManageUserModel::TYPE_SITE_SELECTION_DEVELOPMENT,
//            $request->get('siteSelectionDevelopments'), $relationProvinceCodes);

        OrganizationManageService::checkProvinceIsBand($manageId, $mappingData);
        OrganizationManageService::updateOrganizationById($manageId, $manageData, $mappingData);

        // 审批节点 - 更换省总
        $areaCodes = $request->get('areaCode');
        if ($areaCodes) {
            $orderNos = OpenShopAddressModel::query()->whereIn('provinceCode', $areaCodes)->pluck('orderNo');
            $shopIds  = OpenShopMainProcessModel::query()->whereIn('orderNo', $orderNos)->pluck('shopId')->toArray();
            WorkflowHandlerUserService::changeNodeHandlerUid($shopIds, WorkflowEnum::HANDLER_TYPE_PROVINCE,
                $data['operationUid'], $data['operationName']);
        }

        RmsUserService::delRmsAuthUserInfoCache($data['operationUid']);

        RmsCacheRemote::rmCache(["REMOTE:OrganizationManageRemote:organizationManageList"]);
        return $this->success();
    }

    /**
     * 根据id获取组织信息
     * @param Request $request
     * @param int $manageId
     * @return JsonResponse
     */
    public function getOrganizationInfoById(Request $request, int $manageId): JsonResponse
    {
        $infoById = OrganizationManageService::getOrganizationInfoById($manageId);
        return $this->success($infoById);
    }


    /**
     * @param Request $request
     * @return JsonResponse
     * @throws Exception
     */
    public function userOrganization(Request $request): JsonResponse
    {
        $uid = $request->get("uid");
        OrganizationValidate::userOrganizationValidate(["uid" => $uid]);
        return $this->success(OrganizationManageService::getUserOrganization($uid));
    }


    /**
     * 组织管理列表
     *
     * @return JsonResponse
     * @throws Exception
     */
    public function organizationManageList(): JsonResponse
    {
        return $this->success(OrganizationManageService::organizationManageList());
    }

    /**
     * 地区顾问详情
     * @return JsonResponse
     */
    public function getAreaAdvisor(Request $request, int $manageId): JsonResponse
    {
        return $this->success(
            [
                'provinceCodes'             => OpenShopOrganizationRegionMappingModel::query()->where('manageId', $manageId)
                    ->pluck('provinceCode')->toArray(),
                'provinceDevelopmentUserIds' => OpenShopOrganizationManageUserModel::getData(
                    $manageId,
                    OpenShopOrganizationManageUserModel::TYPE_SITE_SELECTION_DEVELOPMENT
                ),// 省区开发
                'lists'                     => [
                    [
                        'type'     => OpenShopOrganizationManageUserModel::TYPE_INCREASE_MANAGER,// 督导
                        'managers' => OpenShopOrganizationManageUserModel::getData(
                            $manageId,
                            OpenShopOrganizationManageUserModel::TYPE_INCREASE_MANAGER
                        ),
                    ],
                ]
            ]
        );
    }

    /**
     * 地区顾问编辑
     * @param Request $request
     * @param int $manageId
     * @return JsonResponse
     */
    public function setAreaAdvisor(Request $request, int $manageId): JsonResponse
    {
        $request = $request->merge(['manageId' => $manageId]);

        $this->validate($request, [
            'manageId'                                          => 'required|integer',
            'lists'                                             => 'array',
            'lists.*.type'                                      => [
                'required',
                'integer',
                Rule::in([
                    OpenShopOrganizationManageUserModel::TYPE_INCREASE_MANAGER,
                ])
            ],
            'lists.*.managers'                                  => 'array',
            'lists.*.managers.*.userId'                         => 'required|integer',
            'lists.*.managers.*.addressCodesArr'                => 'array',
            'lists.*.managers.*.addressCodesArr.*.provinceCode' => 'string',
            'lists.*.managers.*.addressCodesArr.*.cityCode'     => 'string',
            'lists.*.managers.*.addressCodesArr.*.regionCode'   => 'string',
            'lists.*.managers.*.shopIds'                        => 'array',
        ]);
        $data      = $request->all();
        $rmsUserId = $request->user()->id;
        $isReplace = (int)$request->get('isReplace', 0);// 督导关联门店时 其他门店已经有督导判断 默认0-不替换 1-替换
        $oldUserId = (int)$request->get('oldUserId', 0);// 替换督导时传之前的 督导id

        // 省区开发添加
        OrganizationManageUserService::provinceDevelopmentUser($manageId, $rmsUserId, $data['provinceDevelopmentUserIds'] ?? []);

        // 督导负责区域 目前修改督导可以一个一个配置
        if ($request->get('lists')) {
            foreach ($request->get('lists') as $item) {
                OrganizationManageUserService::changeManager(
                    $request->get('manageId'), $item['type'], $item['managers'] ?? [], [], $rmsUserId, $isReplace, $oldUserId
                );
            }
        }

        return $this->success();
    }

    public function getShopManagers(Request $request)
    {
        $shopId      = (int)$request->get('shopId');
        $managerType = (int)$request->get('managerType');

        $mainProcessId = OpenShopMainProcessModel::query()->where('shopId', $shopId)->orderByDesc('id')->value('id');
        if (!$mainProcessId) {
            BaseService::throwErr('不存在的门店');
        }

        return $this->success(OrderManagerService::getOrderManagerInfo([$mainProcessId], 0, $managerType));
    }

    /**
     * 督导关联门店检验
     * @param Request $request
     * @return JsonResponse
     */
    public function checkManagerShop(Request $request): JsonResponse
    {
        $list = $request->get('list', []);
        if (!$list) {
            BaseService::throwErr('参数不存在');
        }

        return $this->success(OrderManagerService::checkManagerShop($list));
    }

    /**
     * 筛选的门店时，门店开店状态在确认建店之后的才能筛选出来
     * @param Request $request
     * @return JsonResponse
     */
    public function getShops(Request $request): JsonResponse
    {
        return $this->success(MainProcessService::getShopsByStepStatus());
    }
}
